package cn.edu.baiyunu.myapplication.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Matrix
import android.graphics.Paint
import android.net.Uri
import androidx.camera.core.ImageProxy
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 图像处理工具类
 */
object ImageUtils {
    
    /**
     * 将ImageProxy转换为Bitmap
     */
    fun ImageProxy.toBitmap(): Bitmap {
        val buffer = planes[0].buffer
        val bytes = ByteArray(buffer.remaining())
        buffer.get(bytes)
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }
    
    /**
     * 从Uri加载Bitmap
     */
    fun loadBitmapFromUri(context: Context, uri: Uri): Bitmap? {
        return try {
            val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
            inputStream?.use { stream ->
                BitmapFactory.decodeStream(stream)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 将Bitmap保存到文件
     */
    fun saveBitmapToFile(context: Context, bitmap: Bitmap, quality: Int = 95): File? {
        return try {
            // 创建文件名
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "PHOTO_$timeStamp.jpg"
            
            // 创建存储目录
            val storageDir = context.getExternalFilesDir("photos")
            if (!storageDir?.exists()!!) {
                storageDir.mkdirs()
            }
            
            // 创建文件
            val imageFile = File(storageDir, fileName)
            
            // 将位图压缩到文件
            FileOutputStream(imageFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)
            }
            
            imageFile
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 调整Bitmap尺寸
     */
    fun resizeBitmap(bitmap: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        
        val scaleWidth = maxWidth.toFloat() / width
        val scaleHeight = maxHeight.toFloat() / height
        val scale = scaleWidth.coerceAtMost(scaleHeight)
        
        val matrix = Matrix()
        matrix.postScale(scale, scale)
        
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
    }
    
    /**
     * 旋转Bitmap
     */
    fun rotateBitmap(bitmap: Bitmap, degrees: Float): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degrees)
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }
    
    /**
     * 获取Bitmap的质量
     */
    fun getCompressedImageBytes(bitmap: Bitmap, quality: Int = 95): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        return outputStream.toByteArray()
    }
    
    /**
     * 应用简单的滤镜
     */
    fun applySimpleFilters(bitmap: Bitmap, brightness: Float, contrast: Float): Bitmap {
        val resultBitmap = bitmap.copy(bitmap.config ?: Bitmap.Config.ARGB_8888, true)
        
        // 创建ColorMatrix并应用
        val cm = ColorMatrix()
        cm.set(
            floatArrayOf(
                contrast, 0f, 0f, 0f, brightness * 25,
                0f, contrast, 0f, 0f, brightness * 25,
                0f, 0f, contrast, 0f, brightness * 25,
                0f, 0f, 0f, 1f, 0f
            )
        )
        
        val canvas = Canvas(resultBitmap)
        val paint = Paint()
        paint.colorFilter = ColorMatrixColorFilter(cm)
        canvas.drawBitmap(bitmap, 0f, 0f, paint)
        
        return resultBitmap
    }
} 